package cj.web.admin.controllers;

import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.constants.MemuEnum;
import cj.web.admin.constants.ResourceCategoryEnum;
import cj.web.admin.dao.ResourcesDAO;
import cj.web.admin.domain.Contant;
import cj.web.admin.domain.Resources;
import cj.web.login.controllers.BaseController;

@Path("/resources")
public class ResourcesController extends BaseController{

	private static Logger logger = Logger.getLogger(ResourcesController.class.getName());
	
	@Autowired
	private ResourcesDAO resourcesDao;

	@Get("query")
	public String query(Model model,Resources resources)
	{
		resourcesDao.query(resources);
		return null;
	}
	
	@Get("queryById")
	public String queryById(Model model,@Param("id") int id)
	{
		resourcesDao.queryById(id);
		return null;
	}
	
	@Get("resdetail")
	public String showDetail(Model model, @Param("category")String category){
		model.add("category",category);
		
		EnumSet<ResourceCategoryEnum> categoryEnum = EnumSet.allOf(ResourceCategoryEnum.class);		
		model.add("categoryEnum",categoryEnum);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "/views/portal/resourceList.vm";
	}
	
	@Post("conditonQuery")
	public String conditonQuery(Resources condition, @Param("beginAT") String beginDate,@Param("endAT") String endDate){
		if(endDate != null && endDate.length() > 0){
			endDate += " 23:59:59";
		}
		
		List<Resources> ret = resourcesDao.queryConditional(condition, beginDate, endDate);
		
        JSONObject jo = new JSONObject();
		
		int size = resourcesDao.querySize(condition, beginDate, endDate);
		jo.put("data", ret);
		jo.put("draw", condition.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model,@Param("category")String category)
	{
		EnumSet<ResourceCategoryEnum> categoryEnum = EnumSet.allOf(ResourceCategoryEnum.class);		
		model.add("categoryEnum",categoryEnum);
		
		model.add("category",category);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(category));
		return "/views/portal/resourceDetail.vm";
	}
		
	@Post("create")
	public String create(Model model,Resources resources,@Param("umContent") String umContent,HttpServletRequest request)
	{		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		try {
			resources.setContent(umContent);
			resources.setCreateUser(returnSessionObj(request).getAccount());
			resources.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
			resources.setCreateAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
			resources.setReleaseState(Constants.portal.releaseState.state_1);
			resources.setReleaseAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
			resources.setUpdateUser(returnSessionObj(request).getAccount());
			resources.setUpdateAT(DateUtils.getNowTime(DateUtils.DATE_FULL_STR));
			resourcesDao.create(resources);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
		
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id)
	{
		Resources obj = resourcesDao.queryById(id);
		model.add("resource", obj);
		
		EnumSet<ResourceCategoryEnum> categoryEnum = EnumSet.allOf(ResourceCategoryEnum.class);		
		model.add("categoryEnum",categoryEnum);
		//MemuEnum
        model.add("MemuEnum",retMemuValue(obj.getCategory()));
		return "/views/portal/resourceEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,Resources resources,@Param("umContent") String umContent,HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		
		try {
			jo.put("returnFlag", Constants.returnObj.returnFlag_true);
			resources.setContent(umContent);
			resources.setUpdateUser(returnSessionObj(request).getAccount());
			resourcesDao.update(resources);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model, @Param("id") int id) {
		Resources obj = resourcesDao.queryById(id);

		if (obj != null) {
			resourcesDao.deleteById(id);
		}
		
		return "r:resdetail?category="+obj.getCategory();
	}
	
	@Post("doUpload")
    public String doUpload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {  
            try {  
            	// 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 300, 300, true);//缩率图
            } catch (Exception e) {
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	@Get("fileDelete")
    public String fileDelete(@Param("key") String key) {
		JSONObject jo = new JSONObject();
		jo.put("key", key);
		jo.put("id", key);
		return "@"+jo.toString();
	}
	
	/**
	 * 返回菜单
	 * @param category
	 * @return
	 */
	private MemuEnum retMemuValue(String type)
	{
		
		if(type.equals("0"))
		{
			return MemuEnum.hwls;
		}
		if(type.equals("1"))
		{
			return MemuEnum.zxcg;
		}
		if(type.equals("2"))
		{
			return MemuEnum.cyzn;
		}
		if(type.equals("3"))
		{
			return MemuEnum.qygc;
		}
		
		return null;
	}
}
